package com.example.coursesearch;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataRetriever {
	private static final String DB_NAME = "courseDB";
	private static final String TABLE_NAME="courses";
	private static String DB_PATH = "";
	private final Context mContext; 
	protected static final String TAG = "DataRetriever";
	private SQLiteDatabase mDb; 
	private DataBaseHelper mDbHelper; 
	
	public DataRetriever(Context context){
		this.mContext = context;
		this.mDbHelper = new DataBaseHelper(mContext); 
	}
	
	 public DataRetriever createDatabase() throws SQLException  
	    { 
	        try  
	        { 
	            mDbHelper.createDataBase(); 
	            Log.e(TAG, "creating databse in  CreateDatabase"); 
	        }  
	        catch (IOException mIOException)  
	        { 
	            Log.e(TAG, "UnableToCreateDatabase in CreateDatabase"); 
	            throw new Error("UnableToCreateDatabase"); 
	        } 
	        return this; 
	    } 
	 
	
	public DataRetriever open(){ 
        try{ 	 
        	mDbHelper.createDataBase(); 
            mDbHelper.openDataBase(); 
            mDbHelper.close(); 
            mDb = mDbHelper.getReadableDatabase(); 
            Log.e(TAG,  "TYRING TO GET READABLE DATABASE");
        }  
        catch (SQLException mSQLException)  
        { 
            Log.e(TAG, "open >>"+ mSQLException.toString()); 
            throw mSQLException; 
        } catch (IOException mIOException) {
        	 Log.e(TAG, "open >>"+ mIOException.toString()); 
		} 
        return this; 
    }
	
	 public void close(){ 
	        mDbHelper.close(); 
	    }
	 
	 public Cursor getCourseData(String constraint) throws SQLException{ 
		 String queryString = "SELECT * FROM " + TABLE_NAME;
		 if (constraint != null) {
                constraint = constraint.trim() + "%";
                 queryString += " WHERE code LIKE ? LIMIT 5";
             }
             String params[] = { constraint };
             Log.e(TAG, constraint + "CONTSTRAINT");

             if (constraint == null) {
                 params = null;
             }
             try {
            	 Log.e(TAG, constraint + "TYRING TO GET THE CURSOR");
            	 Log.e(TAG, Long.toString(mDb.getPageSize()));
            	 Cursor cursor = mDb.rawQuery(queryString, params);
                 Log.e(TAG, constraint + "TYRING TO QUERY");
                 if (cursor != null) {
                	 Log.e(TAG, constraint + "FOUND SOME");
                     cursor.moveToFirst();
                     Log.e(TAG, constraint + "RETURN CURSOR");
                     return cursor;
                 }
             }
             catch (SQLException e) {
            	 Log.e(TAG, constraint + "FAILED TO QUERY");
                 throw e;
             }
             catch (Exception e) {
				Log.e(TAG, e.toString());
			}
             Log.e(TAG, constraint + "RETURN NULL");
             return null;
         }
 
       
			
	public class DataBaseHelper extends SQLiteOpenHelper{
		private static final String TAG = "DataBaseHelper";
		private SQLiteDatabase mDataBase;   
		
		public DataBaseHelper(Context context) {
			super(context, DB_NAME , null , 1);
			DB_PATH =  context.getApplicationInfo().dataDir + "/databases/"; 
		}
		
		public void createDataBase() throws IOException{ 
		    //If database not exists copy it from the assets 
			boolean mDataBaseExist = checkDataBase(); 
		    
			if(!mDataBaseExist){ 
		        this.getReadableDatabase(); 
		        this.close(); 
		        try{ 
		            //Copy the database from assests 
		            copyDataBase(); 
		            Log.e(TAG, "createDatabase database created"); 
		        }  
		        catch (IOException mIOException){ 
		            throw new Error("ErrorCopyingDataBase"); 
		        } 
		    } 
		} 
		
	    private boolean checkDataBase() 
	    { 
	        File dbFile = new File(DB_PATH + DB_NAME); 
	        //Log.v("dbFile", dbFile + "   "+ dbFile.exists()); 
	        return dbFile.exists(); 
	    } 
	 
	    //Copy the database from assets 
	    private void copyDataBase() throws IOException 
	    { 
	        InputStream mInput = mContext.getAssets().open(DB_NAME); 
	        String outFileName = DB_PATH + DB_NAME; 
	        OutputStream mOutput = new FileOutputStream(outFileName); 
	        byte[] mBuffer = new byte[1024]; 
	        int mLength; 
	        while ((mLength = mInput.read(mBuffer))>0) 
	        { 
	            mOutput.write(mBuffer, 0, mLength); 
	        } 
	        mOutput.flush(); 
	        mOutput.close(); 
	        mInput.close(); 
	    } 
	    
	    public boolean openDataBase() throws SQLException 
	    { 
	        String mPath = DB_PATH + DB_NAME; 
	        //Log.v("mPath", mPath); 
	        mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY); 
	        //mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); 
	        return mDataBase != null; 
	    } 
	 
	    @Override 
	    public synchronized void close()  
	    { 
	        if(mDataBase != null) 
	            mDataBase.close(); 
	        super.close(); 
	    }
		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			
		}
		
		
		
		
		
		
	}
}
